#ifndef MPVPLAYER_H
#define MPVPLAYER_H

#include <QWidget>
#include <QSharedPointer>
#include <mpv/client.h>
#include "m3u8parser.h"

class MpvPlayer : public QWidget
{
    Q_OBJECT
public:
    explicit MpvPlayer(QWidget *parent = nullptr);
    virtual ~MpvPlayer();
    void createMpvPlayer(QWidget *videoWin);
    void stop();
    void start();
    void playLocalVideo(const QString &filename); // 播放视频
    void playHLSVideo(const QString &m3u8_url); // 播放视频
    void setVolume(int64_t volume);
    void setMute(bool flag);
    void setSpeed(double speed);
    void setPos(int64_t sec);
private slots:
    void onMpvEvents(); // 这个槽函数由 wakeup()调用（通过mpv_events信号）

signals:
    void mpvEvents(); // 触发on_mpv_events()槽函数的信号
    void mpvPalyEnd(); // 播放结束的信号
    void durationChangedSignal(int64_t);
    void timePosChangedSignal(int64_t);

    void hlsRequestFailedSignal(const QString);
    void pieceDownloadFailSignal(int idx, const QString &msg);
    void hlsPlayErrorSignal();
    void pieceLoadingSignal();
    void pieceLoadedSignal();
private:
    void handleMpvEvent(mpv_event *event); // 处理mpv事件

    void hlsRequestSuccessSlots();
    void hlsRequestFailedSlots(const QString msg);
    void pieceDownloadSuccessSlots(int idx);
    void pieceDownloadFailSlots(int idx, const QString &msg);
private:
    QWidget *_parent;
    bool _is_hls_video;
    QString _store_dir;
    int _total_duration;
    M3u8Node _cur_piece;
    QSharedPointer<M3u8Parser> _m3u8_parser;
    mpv_handle *_mpv;
};

#endif // MPVPLAYER_H
